package com.xiaomi.baidumap.gank.model;

import android.os.Message;

import com.xiaomi.baidumap.common.ActivityUtils;
import com.xiaomi.baidumap.common.LogUtils;
import com.xiaomi.baidumap.gank.model.network.GankClient;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 16-9-5.
 */
public class GankPresenter {

    private Call<GankResult> resultCall;
    private GankView gankView;

    public GankPresenter(GankView gankView) {
        this.gankView = gankView;
    }

    //视图的处理
    public interface GankView{
        void setDate(List<GankItem> list);

        void showMessage();

        void hideEmptyView();

        void showErrorMessage(String msg);
    }


    public void datePresenter(Date date){

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        //首先网络请求
        resultCall = GankClient.getInstance().getDailyData(year, month, day);
        //异步处理
        resultCall.enqueue(gankCallback);
    }

    private Callback<GankResult> gankCallback = new Callback<GankResult>() {
        @Override
        public void onResponse(Call<GankResult> call, Response<GankResult> response) {
            GankResult gankResult = response.body();
            if (gankResult == null){
                gankView.showErrorMessage("数据为空");
                return;
            }
            if (gankResult.isError() || gankResult.getResult() == null || gankResult.getResult().getAndroidItems().isEmpty()){
                gankView.showMessage();
                return;
            }
            List<GankItem> androidItems = gankResult.getResult().getAndroidItems();
            LogUtils.d(androidItems.size()+"");
            gankView.hideEmptyView();
            gankView.setDate(androidItems);
        }

        @Override
        public void onFailure(Call<GankResult> call, Throwable t) {
                //请求失败
           gankView.showErrorMessage("错误"+t.getMessage());
        }
    };
}
